<template>
  <div class="dashboard-container">
    <!-- 数据卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6" v-for="(item, index) in statistics" :key="item.title" class="stat-col">
        <el-card 
          shadow="hover" 
          :body-style="{ padding: '24px' }"
          class="data-card"
          :class="item.type"
          :style="{ animationDelay: `${index * 0.1}s` }"
        >
          <div class="card-content">
            <div class="icon-wrapper">
              <el-icon><component :is="item.icon" /></el-icon>
            </div>
            <div class="data-wrapper">
              <count-to
                :start-val="0"
                :end-val="item.value"
                :duration="2000"
                class="card-value"
              />
              <div class="card-title">{{ item.title }}</div>
            </div>
            <div class="trend-wrapper">
              <!-- <el-icon :class="index % 2 === 0 ? 'trend-up' : 'trend-down'">
                <component :is="index % 2 === 0 ? icons.CaretTop : icons.CaretBottom" />
              </el-icon> -->
              <!-- <span :class="index % 2 === 0 ? 'trend-up' : 'trend-down'">
                {{ (Math.random() * 10).toFixed(1) }}%
              </span> -->
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    
    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card contribution-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">文章贡献图</span>
            </div>
          </template>
          <ContributionGraph :data="contributionData" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="16">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">浏览趋势</span>
              <div class="chart-actions">
                <el-button 
                  size="small" 
                  :type="chartPeriod === 'week' ? 'primary' : 'default'"
                  @click="switchChartPeriod('week')"
                >
                  近7天
                </el-button>
                <el-button 
                  size="small" 
                  :type="chartPeriod === 'month' ? 'primary' : 'default'"
                  @click="switchChartPeriod('month')"
                >
                  近30天
                </el-button>
              </div>
            </div>
          </template>
          <div ref="lineChartRef" class="chart"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="chart-card pie-chart-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">分类统计</span>
            </div>
          </template>
          <div ref="pieChartRef" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 项目信息展示区域 -->
    <el-row :gutter="20" class="project-info-row">
      <el-col :span="24">
        <el-card shadow="hover" class="project-info-card">
          <div class="project-content">
            <el-row :gutter="30" align="middle">
              <!-- 左侧项目信息 -->
              <el-col :span="16">
                <div class="project-info-left">
                  <div class="project-text">
                    <h2 class="project-title">zzzyh论坛管理系统</h2>
                    <p class="project-description">是一款专注于用户体验和视觉设计的后台管理系统模版</p>
                    <p class="project-tech">使用了 Vue3、Vite、Element Plus 等前沿技术</p>
                  </div>
                </div>
                
                <!-- 链接按钮区域 -->
                <div class="project-links">
                  <el-row :gutter="15" class="links-row">
                    <el-col :span="12">
                      <el-button type="primary" plain class="link-btn" @click="openLink('http://zzzyh.fun/')">
                        <el-icon class="link-icon"><Link /></el-icon>
                        <span>项目官网</span>
                      </el-button>
                    </el-col>
                    <el-col :span="12">
                      <el-button type="success" plain class="link-btn" @click="openLink('http://zzzyh.fun/')">
                        <el-icon class="link-icon"><Document /></el-icon>
                        <span>文档</span>
                      </el-button>
                    </el-col>
                  </el-row>
                  <el-row :gutter="15" class="links-row">
                    <el-col :span="12">
                      <el-button type="warning" plain class="link-btn" @click="openLink('https://gitee.com/zheng-yuhang12')">
                        <el-icon class="link-icon"><Star /></el-icon>
                        <span>Gitee</span>
                      </el-button>
                    </el-col>
                    <el-col :span="12"> 
                      <el-button type="info" plain class="link-btn" @click="openLink('http://zzzyh.fun/')">
                        <el-icon class="link-icon"><ChatDotRound /></el-icon>
                        <span>论坛地址</span>
                      </el-button>
                    </el-col>
                  </el-row>
                </div>
              </el-col>
              
              <!-- 右侧图片展示 -->
              <el-col :span="8">
                <div class="project-image-container">
                  <div class="image-wrapper">
                    <img src="@/assets/logo/draw1-Ce1WF34i.png" alt="项目展示图" class="project-image">
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, shallowRef, onMounted, onUnmounted, computed } from 'vue'
import * as echarts from 'echarts'
import type { EChartsOption } from 'echarts'
import { 
  CaretTop, 
  CaretBottom,
  Document,
  Collection,
  ChatLineRound,
  View,
  Link,
  Star,
  ChatDotRound
} from '@element-plus/icons-vue'
import { defineAsyncComponent } from 'vue'
const CountTo = defineAsyncComponent(() => import('./dashboard/components/CountTo.vue'))
const ContributionGraph = defineAsyncComponent(() => import('./dashboard/components/ContributionGraph.vue'))
import { getDashboardDataApi, getBottomDataApi, getBrowseTrendApi } from '../api/system/index.js'

const icons = {
  Document: Document,
  Collection: Collection,
  ChatLineRound: ChatLineRound,
  View: View,
  CaretTop: CaretTop,
  CaretBottom: CaretBottom,
  Link: Link,
  Star: Star,
  ChatDotRound: ChatDotRound
}

const statistics = ref([
  { 
    title: '文章总数', 
    value: 0, 
    type: 'primary',
    icon: icons.Document
  },
  { 
    title: '用户总数', 
    value: 0, 
    type: 'success',
    icon: icons.Collection
  },
  { 
    title: '留言总数', 
    value: 0, 
    type: 'warning',
    icon: icons.ChatLineRound
  },
  { 
    title: '访问量', 
    value: 0, 
    type: 'info',
    icon: icons.View
  }
])

const contributionData = ref<any[]>([])

// 图表相关
const lineChartRef = ref<HTMLElement | null>(null)
const pieChartRef = ref<HTMLElement | null>(null)
const lineChart = shallowRef<echarts.ECharts | null>(null)
const pieChart = shallowRef<echarts.ECharts | null>(null)

// 图表周期状态
const chartPeriod = ref<'week' | 'month'>('week')

// 生成日期数据的函数
const generateDateRange = (days: number) => {
  const dates: string[] = []
  for (let i = days - 1; i >= 0; i--) {
    const date = new Date()
    date.setDate(date.getDate() - i)
    dates.push(`${date.getMonth() + 1}-${date.getDate()}`)
  }
  return dates
}

// 折线图配置
const getLineChartOption = (seriesData?: number[], period: 'week' | 'month' = 'week'): EChartsOption => {
  // 根据周期生成日期范围
  const dates = period === 'month' ? generateDateRange(30) : generateDateRange(7)

  return {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#e4e7ed',
      borderWidth: 1,
      textStyle: {
        color: '#606266'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates,
      axisLine: {
        lineStyle: {
          color: '#e4e7ed'
        }
      },
      axisLabel: {
        color: '#909399'
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#e4e7ed'
        }
      },
      axisLabel: {
        color: '#909399'
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#f0f0f0'
        }
      }
    },
    series: [
      {
        name: '浏览量',
        type: 'line',
        smooth: true,
        data: seriesData && seriesData.length === dates.length ? seriesData : Array(dates.length).fill(0),
        areaStyle: {
          opacity: 0.3,
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: 'rgba(103, 194, 58, 0.3)'
            }, {
              offset: 1, color: 'rgba(103, 194, 58, 0.01)'
            }]
          }
        },
        itemStyle: {
          color: '#67C23A'
        },
        lineStyle: {
          width: 2
        }
      }
    ]
  }
}

// 切换图表周期
const switchChartPeriod = (period: 'week' | 'month') => {
  chartPeriod.value = period
  updateLineChart()
}

// 更新折线图
const updateLineChart = () => {
  if (lineChart.value) {
    getBrowseTrendApi(chartPeriod.value).then(res => {
      const option = getLineChartOption(res.data, chartPeriod.value)
      lineChart.value!.setOption(option, true)
    })
  }
}

const initChartsChart = () => {
  // 初始化折线图
  if (lineChartRef.value) {
    lineChart.value = echarts.init(lineChartRef.value)
    updateLineChart()
  }
  
  // 初始化饼图
  getBottomDataApi().then(res => {
    if (pieChartRef.value) {
      pieChart.value = echarts.init(pieChartRef.value)
      const option = getPieChartOption()
      if (option.series && Array.isArray(option.series)) {
        option.series[0].data = res.data
      }
      pieChart.value?.setOption(option)
    }
  })
}

// 饼图配置
const getPieChartOption = (): EChartsOption => ({
  tooltip: {
    trigger: 'item',
    backgroundColor: 'rgba(255, 255, 255, 0.9)',
    borderColor: '#e4e7ed',
    borderWidth: 1,
    textStyle: {
      color: '#606266'
    }
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    textStyle: {
      color: '#606266'
    }
  },
  series: [{
    name: '分类统计',
    type: 'pie',
    radius: ['40%', '70%'],
    avoidLabelOverlap: false,
    itemStyle: {
      borderRadius: 10,
      borderColor: '#fff',
      borderWidth: 2
    },
    label: {
      show: false,
      position: 'center'
    },
    emphasis: {
      label: {
        show: true,
        fontSize: 20,
        fontWeight: 'bold',
        color: '#303133'
      }
    },
    labelLine: {
      show: false
    },
    data: [] as any[]
  }]
})

// 初始化图表
const initCharts = () => {
  getBottomDataApi().then(res => {
    if (lineChartRef.value) {
      lineChart.value = echarts.init(lineChartRef.value)
      lineChart.value.setOption(getLineChartOption())
    }
    
    if (pieChartRef.value) {
      pieChart.value = echarts.init(pieChartRef.value)
      const option = getPieChartOption()
      if (option.series && Array.isArray(option.series)) {
        option.series[0].data = res.data
      }
      pieChart.value?.setOption(option)
    }
  })
}

// 处理窗口大小变化
const handleResize = () => {
  lineChart.value?.resize()
  pieChart.value?.resize()
}

// 打开链接的方法
const openLink = (url: string) => {
  window.open(url, '_blank')
}

onMounted(() => {
  getDashboardDataApi().then(res => {
    statistics.value[0].value = res.data.articleCount
    statistics.value[1].value = res.data.userCount
    statistics.value[2].value = res.data.messageCount
    statistics.value[3].value = res.data.visitCount
    contributionData.value = res.data.contributionData
    // initCharts()
    initChartsChart()
  })
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  lineChart.value?.dispose()
  pieChart.value?.dispose()
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

/* 数据卡片样式 */
.stats-row {
  margin-bottom: 20px;
}

.stat-col {
  margin-bottom: 20px;
}

.data-card {
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  height: 100%;
}

.data-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);
}

.data-card.primary {
  border-left: 4px solid #409eff;
}

.data-card.success {
  border-left: 4px solid #67c23a;
}

.data-card.warning {
  border-left: 4px solid #e6a23c;
}

.data-card.info {
  border-left: 4px solid #909399;
}

.card-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.icon-wrapper {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: transform 0.3s;
  background: rgba(64, 158, 255, 0.1);
}

.data-card.success .icon-wrapper {
  background: rgba(103, 194, 58, 0.1);
}

.data-card.warning .icon-wrapper {
  background: rgba(230, 162, 60, 0.1);
}

.data-card.info .icon-wrapper {
  background: rgba(144, 147, 153, 0.1);
}

.icon-wrapper .el-icon {
  font-size: 24px;
  color: #409eff;
}

.data-card.success .icon-wrapper .el-icon {
  color: #67c23a;
}

.data-card.warning .icon-wrapper .el-icon {
  color: #e6a23c;
}

.data-card.info .icon-wrapper .el-icon {
  color: #909399;
}

.icon-wrapper:hover {
  transform: scale(1.1);
}

.data-wrapper {
  flex: 1;
  padding: 0 20px;
}

.card-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 0;
}

.trend-wrapper {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.trend-wrapper .el-icon {
  font-size: 16px;
}

.trend-up {
  color: #67c23a;
}

.trend-down {
  color: #f56c6c;
}

.trend-wrapper span {
  font-size: 12px;
  font-weight: 500;
  margin-top: 4px;
}

/* 卡片动画 */
.data-card {
  animation: slideUp 0.5s ease-out forwards;
  opacity: 0;
  transform: translateY(20px);
}

@keyframes slideUp {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 贡献图卡片 */
.contribution-card {
  border-radius: 12px;
  overflow: hidden;
}

.contribution-card :deep(.el-card__header) {
  border-bottom: 1px solid #ebeef5;
  padding: 16px 20px;
}

/* 图表区域样式 */
.chart-row {
  margin-top: 20px;
}

.chart-card {
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 20px;
}

.chart-card :deep(.el-card__header) {
  border-bottom: 1px solid #ebeef5;
  padding: 16px 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-actions {
  display: flex;
  gap: 10px;
}

.chart {
  height: 350px;
  width: 100%;
}

.pie-chart-card {
  height: 100%;
}

/* 项目信息展示区域 */
.project-info-row {
  margin-top: 20px;
}

.project-info-card {
  border-radius: 12px;
  overflow: hidden;
  background: white;
  color: #303133;
  border: 1px solid #ebeef5;
}

.project-content {
  padding: 30px;
}

.project-info-left {
  display: flex;
  align-items: center;
  margin-bottom: 25px;
}

.project-logo img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 3px solid #ebeef5;
  margin-right: 20px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.project-text {
  flex: 1;
}

.project-title {
  margin: 0 0 10px 0;
  font-size: 28px;
  font-weight: 600;
  color: #303133;
}

.project-description {
  font-size: 16px;
  color: #606266;
  margin: 10px 0;
  line-height: 1.6;
}

.project-tech {
  font-size: 14px;
  color: #909399;
  margin: 10px 0 0 0;
  padding-left: 15px;
  border-left: 3px solid #ebeef5;
}

.project-links {
  margin-top: 20px;
}

.links-row {
  margin-bottom: 15px;
}

.link-btn {
  width: 100%;
  background: #f5f7fa;
  border: 1px solid #ebeef5;
  color: #606266;
  font-weight: 500;
  transition: all 0.3s ease;
}

.link-btn:hover {
  background: #eef1f5;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #dcdfe6;
}

.link-btn .link-icon {
  margin-right: 8px;
  font-size: 16px;
  vertical-align: middle;
}

.link-btn span {
  vertical-align: middle;
}

.project-image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.image-wrapper {
  width: 100%;
  height: 250px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  border: 1px solid #ebeef5;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f7fa;
}

.project-image {
  max-width: 90%;
  max-height: 90%;
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .project-info-left {
    flex-direction: column;
    text-align: center;
  }
  
  .project-logo {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .project-text {
    text-align: center;
  }
  
  .project-tech {
    border-left: none;
    border-top: 3px solid #ebeef5;
    padding-left: 0;
    padding-top: 10px;
  }
}

@media (max-width: 768px) {
  .project-content {
    padding: 20px;
  }
  
  .project-title {
    font-size: 24px;
  }
  
  .project-links .el-col {
    margin-bottom: 10px;
  }
  
  .image-wrapper {
    height: 200px;
  }
}
</style>